<template>
  <div class="project-detail-container">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <div class="header-content">
          <el-avatar 
            :size="32" 
            :src="project?.iconUrl" 
            v-if="project?.iconUrl" 
            shape="square"
          />
          <el-avatar 
            :size="32" 
            v-else 
            shape="square"
            class="default-avatar"
          >
            {{ project?.name?.charAt(0).toUpperCase() }}
          </el-avatar>
          <div class="header-text">
            <h2>{{ project?.name }}</h2>
            <p v-if="project?.description">{{ project.description }}</p>
          </div>
        </div>
      </template>
      <template #extra>
        <div class="header-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button type="primary" @click="goToEndpointMonitor">
            <el-icon><Monitor /></el-icon>
            接口监控
          </el-button>
          <el-dropdown @command="handleAction">
            <el-button>
              操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">
                  <el-icon><Edit /></el-icon>
                  编辑项目
                </el-dropdown-item>
                <el-dropdown-item command="delete" divided>
                  <el-icon><Delete /></el-icon>
                  删除项目
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
    </el-page-header>

    <!-- 编辑项目对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑项目" width="50%">
      <div class="edit-project-form">
        <el-form :model="editForm" label-width="120px" @submit.prevent="submitForm" ref="editFormRef">
          <el-form-item label="项目名称">
            <el-input v-model="editForm.name" />
          </el-form-item>
          <el-form-item label="项目描述">
            <el-input v-model="editForm.description" type="textarea" :rows="4" />
          </el-form-item>
          <el-form-item label="项目图标">
            <div class="avatar-uploader">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <el-avatar
                  v-if="editForm.iconUrl"
                  :size="80"
                  :src="editForm.iconUrl"
                  shape="square"
                />
                <el-avatar
                  v-else
                  :size="80"
                  shape="square"
                  class="default-avatar"
                >
                  <el-icon :size="32"><Upload /></el-icon>
                </el-avatar>
              </el-upload>
              <div class="avatar-tip">点击上传项目图标</div>
            </div>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="editForm.status" placeholder="请选择状态">
              <el-option label="活跃" value="active" />
              <el-option label="非活跃" value="inactive" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <div class="content-container">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="info-card">
            <template #header>
              <div class="card-header">
                <el-icon><InfoFilled /></el-icon>
                <span>项目信息</span>
              </div>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="项目名称">{{ project?.name }}</el-descriptions-item>
              <el-descriptions-item label="项目描述">{{ project?.description || '无' }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDate(project?.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="最后更新">{{ formatDate(project?.updatedAt) }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="project?.status === 'active' ? 'success' : 'info'">
                  {{ project?.status === 'active' ? '活跃' : '非活跃' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="stats-card">
            <template #header>
              <div class="card-header">
                <el-icon><DataAnalysis /></el-icon>
                <span>统计数据</span>
              </div>
            </template>
            <div class="stats-content">
              <div class="stat-item">
                <div class="stat-label">接口总数</div>
                <div class="stat-value">{{ project?.endpointCount || 0 }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">正常接口</div>
                <div class="stat-value success">{{ project?.healthyEndpoints || 0 }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">异常接口</div>
                <div class="stat-value danger">{{ project?.unhealthyEndpoints || 0 }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown,
  Edit,
  Delete,
  Monitor,
  InfoFilled,
  DataAnalysis,
  Upload
} from '@element-plus/icons-vue'
import api from '../services/api'

export default {
  name: 'ProjectDetail',
  components: {
    ArrowDown,
    Edit,
    Delete,
    Monitor,
    InfoFilled,
    DataAnalysis,
    Upload
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()
    const project = ref(null)
    const loading = ref(false)
    const editDialogVisible = ref(false)
    const editFormRef = ref(null)

    const editForm = reactive({
      name: '',
      description: '',
      iconUrl: '',
      status: 'active'
    })

    const uploadedFile = ref(null) // 保存上传的文件

    // 获取项目详情
    const fetchProject = async () => {
      loading.value = true
      try {
        const response = await api.get(`/projects/${props.id}`)
        project.value = {
          ...response.data,
          endpointCount: Math.floor(Math.random() * 20) + 1, // 模拟接口数量
          healthyEndpoints: Math.floor(Math.random() * 15) + 1, // 模拟正常接口数
          unhealthyEndpoints: Math.floor(Math.random() * 5), // 模拟异常接口数
          status: Math.random() > 0.3 ? 'active' : 'inactive' // 模拟状态
        }
      } catch (error) {
        ElMessage.error('获取项目详情失败: ' + error.message)
        // 使用模拟数据以便展示
        project.value = {
          id: props.id,
          name: '示例项目',
          description: '这是一个示例项目描述',
          createdAt: '2023-01-15T10:30:00Z',
          updatedAt: '2023-06-20T14:20:00Z',
          endpointCount: 15,
          healthyEndpoints: 13,
          unhealthyEndpoints: 2,
          status: 'active'
        }
      } finally {
        loading.value = false
      }
    }

    // 返回项目列表
    const goBack = () => {
      router.push('/')
    }

    // 跳转到接口监控页面
    const goToEndpointMonitor = () => {
      router.push({
        name: 'EndpointMonitor',
        params: { projectId: props.id }
      })
    }

    // 处理操作命令
    const handleAction = (command) => {
      switch (command) {
        case 'edit':
          // 填充编辑表单
          editForm.name = project.value.name
          editForm.description = project.value.description || ''
          editForm.iconUrl = project.value.iconUrl || ''
          editForm.status = project.value.status
          editDialogVisible.value = true
          break
        case 'delete':
          deleteProject()
          break
      }
    }

    // 处理头像上传
    const handleAvatarUpload = async (options) => {
      const { file } = options
      uploadedFile.value = file // 保存文件以备后续上传

      // 显示预览
      const reader = new FileReader()
      reader.onload = (e) => {
        editForm.iconUrl = e.target.result
        ElMessage.success('图标已选择，保存后将上传到云端')
      }
      reader.readAsDataURL(file)
    }

    // 上传前检查
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('头像图片大小不能超过 2MB!')
      }

      return isJPG && isLt2M
    }

    // 提交编辑表单
    const submitForm = async () => {
      try {
        // 先更新项目基本信息（不包含图标）
        const updatedProject = {
          name: editForm.name,
          description: editForm.description,
          status: editForm.status
        }

        const response = await api.put(`/projects/${props.id}`, updatedProject)
        project.value = { ...project.value, ...response.data }

        // 如果有上传的文件，则上传图标到七牛云
        if (uploadedFile.value) {
          const formData = new FormData()
          formData.append('file', uploadedFile.value)

          const iconResponse = await api.post(`/projects/${props.id}/icon`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })

          // 更新项目图标URL
          project.value.iconUrl = iconResponse.data
        }

        editDialogVisible.value = false
        ElMessage.success('项目更新成功')
      } catch (error) {
        console.error('更新项目失败:', error)
        ElMessage.error('更新项目失败: ' + error.message)
      }
    }

    // 删除项目
    const deleteProject = () => {
      ElMessageBox.confirm(
        `确定要删除项目 "${project.value.name}" 吗？此操作不可恢复。`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await api.delete(`/projects/${props.id}`)
          ElMessage.success('删除项目成功')
          router.push('/')
        } catch (error) {
          ElMessage.error('删除项目失败: ' + error.message)
        }
      }).catch(() => {
        // 用户取消删除
      })
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    onMounted(() => {
      fetchProject()
    })

    return {
      project,
      loading,
      editDialogVisible,
      editFormRef,
      editForm,
      goBack,
      goToEndpointMonitor,
      handleAction,
      submitForm,
      deleteProject,
      formatDate,
      handleAvatarUpload,
      beforeAvatarUpload
    }
  }
}
</script>

<style scoped>
.project-detail-container {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  background-color: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.default-avatar {
  background-color: #e8d8a8;
  color: #cdaa52;
}

.header-text h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.header-text p {
  margin: 4px 0 0 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.content-container {
  padding: 0 24px;
}

.info-card, .stats-card {
  border: 1px solid #e0d4b4;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.stats-content {
  padding: 20px 0;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.danger {
  color: #f56c6c;
}

.edit-project-form {
  padding: 20px;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.avatar-tip {
  color: #999;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-page-header__content) {
  font-size: 20px;
}

:deep(.el-page-header__title) {
  font-size: 14px;
}

:deep(.el-card__header) {
  border-bottom: 1px solid #e0d4b4;
  padding: 16px 20px;
}
</style>